import createStore from "ipreact-for-react";
import { createBrowserHistory } from 'history'
import { MenuKey, menu_map } from "./menu";
import { _ROOT_ } from "./utils/consts";
import { message } from "antd";
import { RouterParam } from "./typings";

export const history = createBrowserHistory<TabItem>({
    basename: _ROOT_
})
const STORE_KEY = 'CREATE@TABS@APP'
export interface Rect {
    width: number,
    height: number,
}
export interface TabItem {
    menuKey: MenuKey,
    /** 唯一 */
    pathname: string,
    title?: string,
    params?: Record<string, string>
}
export interface IStoreState {
    loading?: number
    collapsed?: boolean
    pathname?: string
    rect?: Rect
    top?: number
    tabs: TabItem[]
}

const store: IStoreState = {
    loading: 0,
    collapsed: false,
    top: document.getElementById('app').getBoundingClientRect().top,
    rect: {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight,
    },
    tabs: [
        { menuKey: MenuKey.USERS, pathname: MenuKey.USERS }
    ],
    pathname: MenuKey.USERS,
}
try {
    Object.assign(store, JSON.parse(localStorage.getItem(STORE_KEY)))
} catch (e) {
    // TO Nothing
}

const { connect, dispatch, getState } = createStore<IStoreState>([
    (prevState, currentState) => {
        const { collapsed, tabs, pathname } = currentState
        localStorage.setItem(STORE_KEY, JSON.stringify({ collapsed, tabs, pathname }))
    }
])({
    ...store,
    pathname: /\w/.test(history.location.pathname) ? history.location.pathname : undefined
})

export { connect, dispatch, getState }

const resize = function resize () {
	dispatch((state) => ({
		...state,
		rect: {
			width: document.documentElement.clientWidth,
			height: document.documentElement.clientHeight,
		},
	}));
};
addEventListener('resize', resize);

/** 修改标签标题 */
export const changeTitle = (title: string) => dispatch(state => {
    const { tabs, pathname } = state
    return {
        ...state,
        tabs: tabs.map(t => {
            if (t.pathname === pathname) {
                return { ...t, title }
            }
            return t
        })
    }
})
export const renderHref = <T extends MenuKey>(...args: RouterParam<T> extends never ? [T] : [T, RouterParam<T>]) => {
    const [ key, params ] = args
    return !params ? key : key.replace(/:\w+/g, k => params[k.slice(1)])
}
/** 主要跳转函数 */
export const openTab = <T extends MenuKey>(...args: RouterParam<T> extends never ? [T] : [T, RouterParam<T>]) => {
    const [ key, params ] = args
    const url = renderHref.apply(null, [key, params])
    if (url === history.location.pathname) {
        return
    }
    const menu = menu_map.get(key)
    if (!menu) {
        message.error('不存在的路由!')
        return
    }
    history.push(url)
}

export const closeTab = (pathname?: string) => {
    pathname = pathname || history.location.pathname
    const { tabs } = getState()
    if (pathname === history.location.pathname) {
        const index = tabs.findIndex(t => t.pathname === pathname)
        if (index === tabs.length - 1) {
            if (index > 0) {
                const prev = tabs[index - 1]
                history.push(prev.pathname)
            } else {
                history.push('/')
            }
        } else {
            const next = tabs[index + 1]
            history.push(next.pathname)
        }
    }
    dispatch(state => {
        return {
            ...state,
            tabs: state.tabs.filter(t => t.pathname != pathname)
        }    
    })
}

export const closeTabOthers = () => {
    dispatch(state => {
        const { tabs, pathname } = state
        const tab = tabs.find(t => t.pathname === pathname)
        return {
            ...state,
            tabs: [tab]
        }
    })
}

export const closeTabAll = () => {
    history.push('/')
    dispatch(state => {
        return {
            ...state,
            tabs: [],
        }
    })
}